<template>
  <div>
    <!-- 页面导航 -->
    <a-breadcrumb style="margin-bottom: 10px">
      <a-breadcrumb-item>
        <icon-menu-unfold />
      </a-breadcrumb-item>
      <a-breadcrumb-item>光伏设备</a-breadcrumb-item>
      <a-breadcrumb-item>变量列表</a-breadcrumb-item>
    </a-breadcrumb>

    <a-card>
      <a-row>
        <!-- 标签页 -->
        <a-col>
          <a-tabs v-model:active-key="tabsActiveKey" @change="handleTabsChange">
            <a-tab-pane v-for="(item, index) in tabsList" :key="item.key" :title="item.title" />
          </a-tabs>
        </a-col>

        <!-- 查询条件 -->
        <a-row>
          <a-col :flex="1">
            <a-form :model="searchModel" :label-col-props="{ span: 6 }" :wrapper-col-props="{ span: 18 }" label-align="left" auto-label-width>
              <a-row :gutter="16">
                <a-col :span="11">
                  <a-form-item field="catalogId" label="设备名称">
                    <a-tree-select allow-clear allow-search v-model="searchModel.deviceId" :fieldNames="catalogIdFieldNames" :data="deviceData" placeholder="请选择" />
                  </a-form-item>
                </a-col>
                <a-col :span="11">
                  <a-form-item field="deviceName" label="变量名称">
                    <a-input v-model="searchModel.varName" placeholder="请输入" allow-clear />
                  </a-form-item>
                </a-col>
                <a-col :span="2">
                  <a-space direction="vertical" :size="18">
                    <a-button type="primary" @click="search">
                      <template #icon>
                        <icon-search />
                      </template>
                      {{ '查询' }}
                    </a-button>
                  </a-space>
                </a-col>
              </a-row>
            </a-form>
          </a-col>
        </a-row>

        <!-- 分割线 -->
        <a-divider style="margin-top: 0" />

        <!-- 表格 -->
        <a-table :loading="loading" size="medium" row-key="id" :bordered="{ wrapper: true, cell: true }"
                 :pagination="pagination"
                 :columns="tabColumns"
                 :data="renderData"
                 @page-change="onPageChange"
                 @page-size-change="onPageSizeChange">
          <!-- 变量类型 -->
          <template #varType="{ record }">
            <span v-if="record.varType === 2">{{ '不指定' }}</span>
            <span v-else>{{ '电能发电' }}</span>
          </template>

          <!-- 是否修正 -->
          <template #dataFix="{ record }">
            <a-tag v-if="record.dataFix" color="rgb(var(--red-6))">是</a-tag>
            <a-tag v-else color="rgb(var(--primary-6))">否</a-tag>
          </template>

          <!-- 是否累积 -->
          <template #isAccumulation="{ record }">
            <a-tag v-if="record.isAccumulation == 0" color="rgb(var(--primary-6))">否</a-tag>
            <a-tag v-else color="rgb(var(--red-6))">是</a-tag>
          </template>

          <!-- 数据来源 -->
          <template #origin="{ record }">
            <a-tag v-if="record.origin == 1" color="rgb(var(--primary-6))">IO型</a-tag>
          </template>

          <!-- 数据类型 -->
          <template #dataType="{ record }">
            <a-tag v-if="record.dataType == 19" color="rgb(var(--primary-6))">4字节浮点4321</a-tag>
          </template>

          <!-- 存盘周期 -->
          <template #saveCycle="{ record }">
            <a-tag color="rgb(var(--primary-6))">{{ record.saveCycle + `分钟` }}</a-tag>
          </template>

          <!-- 状态 -->
          <template #stopFlag="{ record }">
            <stopFlag :value="record.stopFlag" />
          </template>

          <!-- 操作 -->
          <template #operate="{ record }">
            <a-button size="small" type="text" @click="handleStopFlag(record)" :status="record.stopFlag == 1 ? 'normal' : 'warning'">
              {{ record.stopFlag == 0 ? '停用' : '启用' }}
            </a-button>
            <a-button size="small" type="text" status="danger" @click="handleDelete(record)">{{ '删除' }}</a-button>
            <a-button size="small" type="text" @click="handleDeviceDetail(record)">{{ '详情' }}</a-button>
          </template>
        </a-table>
      </a-row>
    </a-card>

    <!-- 操作弹框 -->
    <a-modal width="450px" v-model:visible="operateModalModel.visible" class="modal-box">
      <template #title>
        <icon-close-circle v-if="operateModalModel.type == 1" size="18" style="color: rgb(var(--red-6)); margin-right: 5px" />
        <icon-exclamation-circle v-else size="18" style="color: rgb(var(--orange-6)); margin-right: 5px" />
        确认提示
      </template>
      <div style="text-align: center">是否确认{{ operateModalModel.title }}名称为【{{ operateModalModel.name }}】的数据项？</div>
      <template #footer>
        <div style="text-align: center">
          <a-space>
            <a-button type="primary" status="danger" @click="handleOperateModelCancle">取消</a-button>
            <a-button type="primary" @click="handleOperateModelOk">确认</a-button>
          </a-space>
        </div>
      </template>
    </a-modal>

    <!-- 详情右弹层 -->
    <a-drawer :width="1000" :title="formDrawer.title" :visible="formDrawer.visible" hide-cancel unmountOnClose :mask-closable="false" @cancel="handleDrawerCancel" @ok="handleDrawerCancel">
      <a-row :gutter="24" style="padding: 0 20px">
        <a-col :span="12">
          <a-divider orientation="left">变量信息</a-divider>
          <a-descriptions
              :align="{ label: 'right' }"
              :label-style="{
              color: 'rgb(var(--color-neutral-10))'
            }"
              :data="formDrawer.varInfo"
              :column="1"
              size="large"
          >
            <template #value="{ value }">
              <a-skeleton v-if="formDrawer.loading" :animation="true">
                <a-skeleton-line :rows="1" />
              </a-skeleton>
              <span v-else>{{ value }}</span>
            </template>
          </a-descriptions>

          <a-divider orientation="left">数据来源</a-divider>
          <a-descriptions :align="{ label: 'right' }" :label-style="{ color: 'rgb(var(--color-neutral-10))' }" :data="formDrawer.dataSource" :column="1" size="large">
            <template #value="{ value }">
              <a-skeleton v-if="formDrawer.loading" :animation="true">
                <a-skeleton-line :rows="1" />
              </a-skeleton>
              <span v-else>{{ value }}</span>
            </template>
          </a-descriptions>
        </a-col>

        <a-col :span="12">
          <a-divider orientation="left">数据处理</a-divider>
          <a-descriptions :align="{ label: 'right' }" :label-style="{ color: 'rgb(var(--color-neutral-10))' }" :data="formDrawer.dataHandle" :column="1" size="large">
            <template #value="{ value }">
              <a-skeleton v-if="formDrawer.loading" :animation="true">
                <a-skeleton-line :rows="1" />
              </a-skeleton>
              <span v-else>{{ value }}</span>
            </template>
          </a-descriptions>

          <a-divider orientation="left">系统信息</a-divider>
          <a-descriptions :align="{ label: 'right' }" :label-style="{ color: 'rgb(var(--color-neutral-10))' }" :data="formDrawer.systemInfo" :column="1" size="large">
            <template #value="{ value }">
              <a-skeleton v-if="formDrawer.loading" :animation="true">
                <a-skeleton-line :rows="1" />
              </a-skeleton>
              <span v-else>{{ value }}</span>
            </template>
          </a-descriptions>
        </a-col>
      </a-row>
    </a-drawer>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue';
import { listFusionGroup, listDeviceVar } from '../../apis/device';
import { processSelectable } from '../../utils/tableUtil';
import useLoading from '../../utils/loading';
import stopFlag from '../../components/stop-flag/index.vue';
import { BasePagination } from '../../apis/common';

// 加载状态管理
const { loading, setLoading } = useLoading(true);

// 标签页配置
const tabsList = ref([
  { key: 1, title: '模拟量' },
  { key: 2, title: '状态量' }
]);

// 当前选中的标签页
const tabsActiveKey = ref<number>(1);

// 标签页切换处理
const handleTabsChange = async () => {
  // 重置页码
  pagination.current = 1;
  // 重置表格数据
  await fetchData();
};

// 设备树选择器字段配置
const catalogIdFieldNames = ref({
  key: 'key',
  title: 'deviceName',
  children: 'children'
});

// 生成查询条件模型
const generateSearchModel = () => {
  return {
    varName: '',
    deviceId: undefined
  };
};

// 查询表单模型
const searchModel = ref(generateSearchModel());

// 设备数据
const deviceData = ref([]);

// 获取设备列表
const fetchDeviceData = async () => {
  try {
    const res = await listFusionGroup({
      stationType: 2
    });
    if (res.data.code === 200) {
      deviceData.value = res.data.data;
      // 设置下拉选择框显示中文
      processSelectable(res.data.data);
    }
  } catch (err) {
    console.error('获取设备列表失败', err);
  }
};

// 组件挂载时初始化
onMounted(async () => {
  await fetchDeviceData();
  await fetchData();
});

// 接收父组件传递的参数
const props = defineProps({
  stationType: {
    type: Number,
    default: 2
  }
});

// 表格分页配置
const pagination = reactive({ ...BasePagination() });

// 表格列配置
const tabColumns = computed(() => [
  { title: '变量名称', dataIndex: 'varName', fixed: 'left', width: 120, align: 'left' },
  { title: '变量编码', fixed: 'left', width: 120, dataIndex: 'varSn', align: 'left', ellipsis: true, tooltip: { position: 'top' } },
  { title: '变量类型', width: 80, dataIndex: 'varType', slotName: 'varType', align: 'center' },
  { title: '是否修正', width: 80, dataIndex: 'dataFix', slotName: 'dataFix', align: 'center' },
  { title: '是否累积', width: 80, dataIndex: 'isAccumulation', slotName: 'isAccumulation', align: 'center' },
  { title: '监控设备', width: 80, dataIndex: 'deviceName', align: 'left' },
  { title: '所属通道', width: 90, dataIndex: 'channelName', align: 'center' },
  { title: '数据来源', width: 80, dataIndex: 'origin', slotName: 'origin', align: 'center' },
  { title: '数据地址', width: 80, dataIndex: 'messageAddress', align: 'center' },
  { title: '数据类型', width: 120, dataIndex: 'dataType', slotName: 'dataType', align: 'center' },
  { title: '系数', width: 60, dataIndex: 'coefficient', align: 'center' },
  { title: '存盘周期', width: 80, dataIndex: 'saveCycle', slotName: 'saveCycle', align: 'center' },
  { title: '启用状态', width: 80, dataIndex: 'stopFlag', slotName: 'stopFlag', align: 'center', fixed: 'right' },
  { title: '操作', dataIndex: 'operations', width: 200, slotName: 'operate', align: 'center', fixed: 'right' }
]);

// 表格数据
const renderData = ref([]);

// 页码变化处理
const onPageChange = async (val: number) => {
  pagination.current = val;
  await fetchData();
};

// 每页数量变化处理
const onPageSizeChange = async (val: number) => {
  pagination.pageSize = val;
  await fetchData();
};

// 获取表格数据
const fetchData = async () => {
  setLoading(true);
  try {
    const res = await listDeviceVar({
      pageSize: pagination.pageSize,
      pageNum: pagination.current,
      ...searchModel.value,
      ...props,
      varType: tabsActiveKey.value
    });
    if (res.data.code === 200) {
      renderData.value = res.data.rows;
      pagination.total = res.data.total;
    }
  } catch (err) {
    console.error('获取表格数据失败', err);
  } finally {
    setLoading(false);
  }
};

// 查询处理
const search = async () => {
  pagination.current = 1;
  await fetchData();
};

// 操作弹框模型生成
const generateOperateModalModel = () => {
  return {
    type: 0,        // 0: 状态变更, 1: 删除
    visible: false, // 弹框可见性
    title: '',      // 操作标题
    id: 0,          // 数据ID
    value: 0,       // 操作值
    name: ''        // 数据名称
  };
};

// 操作弹框模型
const operateModalModel = ref(generateOperateModalModel());

// 处理停用/启用操作
const handleStopFlag = (record: any) => {
  operateModalModel.value.visible = true;
  operateModalModel.value.id = record.id;
  operateModalModel.value.title = record.stopFlag === 0 ? '停用' : '启用';
  operateModalModel.value.name = record.varName;
  operateModalModel.value.value = record.stopFlag === 0 ? 1 : 0;
  operateModalModel.value.type = 0;
};

// 处理删除操作
const handleDelete = (record: any) => {
  operateModalModel.value.visible = true;
  operateModalModel.value.id = record.id;
  operateModalModel.value.title = '删除';
  operateModalModel.value.name = record.varName;
  operateModalModel.value.type = 1;
};

// 操作弹框取消处理
const handleOperateModelCancle = () => {
  operateModalModel.value = generateOperateModalModel();
};

// 操作弹框确认处理
const handleOperateModelOk = () => {
  // 停用/启用操作
  if (operateModalModel.value.type === 0) {
    for (let i = 0; i < renderData.value.length; i++) {
      if (renderData.value[i].id === operateModalModel.value.id) {
        renderData.value[i].stopFlag = operateModalModel.value.value;
      }
    }
  }
  // 删除操作
  if (operateModalModel.value.type === 1) {
    renderData.value.forEach((item: any, index: number) => {
      if (item.varName === operateModalModel.value.name) {
        renderData.value.splice(index, 1);
      }
    });
  }
  // 关闭弹框
  operateModalModel.value.visible = false;
};

// 生成详情抽屉模型
const generateFormDrawerModel = () => {
  return {
    visible: false,    // 抽屉可见性
    loading: false,    // 加载状态
    title: '',         // 标题
    varInfo: [],       // 变量信息
    dataSource: [],    // 数据来源信息
    dataHandle: [],    // 数据处理信息
    systemInfo: []     // 系统信息
  };
};

// 详情抽屉模型
const formDrawer = ref(generateFormDrawerModel());

// 处理详情查看
const handleDeviceDetail = (record: any) => {
  formDrawer.value.visible = true;
  formDrawer.value.title = record.varName;

  // 构造详情数据
  let varInfo = [
    { label: '所属站点:', value: '某光伏发电站' },
    { label: '电站类型:', value: '光伏' },
    { label: '所属通道:', value: record.channelName },
    { label: '通讯设备:', value: record.deviceName },
    { label: '变量名称:', value: record.varName },
    { label: '变量编码:', value: record.varSn },
    { label: '启用状态:', value: record.stopFlag == 0 ? '启用' : '停用' }
  ];

  let dataSource = [
    { label: '来源类型:', value: record.origin == 1 ? 'IO型' : '其他' },
    { label: '数据地址:', value: record.messageAddress || '-' }
  ];

  let dataHandle = [
    { label: '数据类型:', value: record.dataType == 19 ? '4字节浮点4321' : '-' },
    { label: '初始赋值:', value: record.initValue || '-' },
    { label: '数据基值:', value: record.baseValue || '-' },
    { label: '数据系数:', value: record.coefficient || '-' },
    { label: '存盘周期:', value: record.saveCycle + `分钟` },
    { label: '是否累积量:', value: record.isAccumulation == 0 ? '否' : '是' },
    { label: '是否修正:', value: record.dataFix == 0 ? '否' : '是' }
  ];

  let systemInfo = [
    { label: '创建人员:', value: record.createBy || '-' },
    { label: '创建时间:', value: record.createTime || '-' },
    { label: '更新人员:', value: record.updateBy || '-' },
    { label: '更新时间:', value: record.updateTime || '-' }
  ];

  formDrawer.value.varInfo = varInfo;
  formDrawer.value.dataSource = dataSource;
  formDrawer.value.dataHandle = dataHandle;
  formDrawer.value.systemInfo = systemInfo;
};

// 关闭详情抽屉
const handleDrawerCancel = () => {
  formDrawer.value = generateFormDrawerModel();
};
</script>